/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.hnilica.cisteniulic.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.hnilica.cisteniulic.exception.ParsingExcelMyException;
import net.hnilice.cisteniulic.excel.ExcelEngine;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;

/**
 *
 * @author swosh
 */
public class AdminTermin extends HttpServlet {

    private static final String url = "/admin/index.jspx?akce=administrace";
    private static final int maxSize = 1024 * 1024 * 50;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ExcelEngine excelEngine = new ExcelEngine();
        InputStream is = null;
        String action = null;
        String actionLocalized;
        String fileName = null;
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.checkRole("uzivatel");
            request.setAttribute("chybaatermin", "");
            request.setAttribute("uspechatermin", "");



            DiskFileUpload fu = new DiskFileUpload();
            fu.setSizeMax(maxSize);
            fu.setSizeThreshold(1024);
            fu.setRepositoryPath(System.getProperty("java.io.tmpdir"));
            List fileList = fu.parseRequest(request);


            String uploadedFileName = null; // name of file on user's computer
            for (Iterator i = fileList.iterator(); i.hasNext();) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    if (fi.getSize() < 1) {
                        try {

                            throw new Exception("No file was uplaoded");

                        } catch (Exception ex) {
                            request.setAttribute("chybaatermin", "Žádný soubor nebyl nahrán");
                            Logger.getLogger(AdminTermin.class.getName()).log(Level.SEVERE, null, ex);
                            return;
                        }
                    } else if (!(fi.getContentType().equalsIgnoreCase("application/vnd.ms-excel")
                            || fi.getContentType().equalsIgnoreCase("application/x-excel")
                            || fi.getContentType().equalsIgnoreCase("application/excel")
                            || fi.getContentType().equalsIgnoreCase("application/x-msexcel")
                            || fi.getContentType().equalsIgnoreCase("application/ms-excel"))) {
                        try {

                            throw new Exception("File is not in format application/vnd.ms-excel, application/x-excel, "
                                    + "application/excel, application/x-msexcel, application/ms-excel.");

                        } catch (Exception ex) {
                            request.setAttribute("chybaatermin", "Soubor není v požadovaném formátu Microsoft Excel 97/2000/XP/2003 formátu.");
                            Logger.getLogger(AdminTermin.class.getName()).log(Level.SEVERE, null, ex);
                            return;
                        }
                    } else {
                        is = fi.getInputStream();
                        fileName = fi.getName();

                    }



                } else if (fi.getFieldName().equalsIgnoreCase("action")) {
                    action = fi.getString();

                }
            }

        } catch (FileUploadException ex) {
            request.setAttribute("chybaatermin", "Soubor se nepovedlo nahrát.");
            Logger.getLogger(AdminTermin.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
        if ("".equals(request.getAttribute("chybaatermin"))) {
            List info = null;
            try {

                if (action.equalsIgnoreCase("update")) {
                    info = excelEngine.update(is);
                    actionLocalized = "aktualizace";
                } else if (action.equalsIgnoreCase("delete")) {
                    info = excelEngine.delete(is);
                    actionLocalized = "mazání";
                } else {
                    info = excelEngine.save(is);
                    actionLocalized = "ukládání";
                }
            } catch (ParsingExcelMyException ex) {
                request.setAttribute("chybaatermin", ex.getMessage());
                // Logged before
                return;
            }
            if (info.isEmpty()) {
                info.add("Soubor byl prázdný.");
                request.setAttribute("uspechatermin", info);
            } else {
                request.setAttribute("uspechatermin", info);
            }
            info.add(0, "Byl zpracován soubor " + fileName + " na zvloenou akci: " + actionLocalized);
            return;
        }



    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/xhtml+xml;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        processRequest(request, response);
        RequestDispatcher dispatcher = request.getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
